package com.sakura.system.exception;


import com.sakura.system.coommon.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 系统异常
 */

@ControllerAdvice(basePackages = "com.gonglidong.systemstudent.controller")
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 拦截业务异常，返回业务异常信息
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleBusinessError(BusinessErrorException ex) {
//        String code = ex.getCode();
        String message = ex.getMessage();
//        return new Result(code, message);
        return Result.error(message);
    }

    /**
     * 空指针异常
     * @param ex NullPointerException
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleTypeMismatchException(NullPointerException ex) {
        logger.error("空指针异常，{}", ex.getMessage());
        return Result.error("500");
    }

    /**
     * 系统异常 预期以外异常
     *
     * Exception,所有u异常鼻祖
     *
     * @pimport com.gonglidong.system.course.exception.BusinessErrorException;aram ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
//    public BusinessMsgEnum handleUnexpectedServer(HttpServletRequest request, Exception ex) {
//        logger.error("系统异常：", ex);
//        return BusinessMsgEnum.UNEXPECTED_EXCEPTION;
//    }
    public Result handleUnexpectedServer(HttpServletRequest request, Exception ex) {
        logger.error("系统异常：", ex);
        return Result.error("系统异常！");
    }

}
